<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="结算明细"
                    name="billingDetails"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        :rules="formDataRules"
                                        ref="formDataRef"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="结算编号">
                                                    {{ formData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="结算日期">
                                                    {{formData.billDate}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="结算单位"
                                                    prop="settleUnit"
                                                >
                                                    {{ formData.settleUnit }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="调动单"
                                                    prop="transferMonad"
                                                >
                                                    {{formData.transferMonad}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="经办人"
                                                    prop="responsiblePerson"
                                                >
                                                   {{formData.responsiblePerson}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="发票编号"
                                                    prop="invoiceBill"
                                                >
                                                    {{formData.invoiceBill}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税率%"
                                                    prop="taxRate"
                                                >
                                                    {{formData.taxRate}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税额(元)"
                                                    prop="taxMoney"
                                                >
                                                    {{formData.taxMoney}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <!-- 结算金额（不含税）+税额 -->
                                                <el-form-item
                                                    label="结算金额(不含税)"
                                                    prop="noTaxMoney"
                                                >
                                                    {{ formData.noTaxMoney }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <!-- 结算明细获取当月租金+操作手工资+进场费+退场费+加扣款的汇总 -->
                                                <el-form-item
                                                    label="结算金额"
                                                    prop="settleMoney"
                                                >
                                                    {{ formData.settleMoney }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="机构"
                                                    prop="orgName"
                                                >
                                                    {{ formData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="传输财务共享"
                                                    prop="share"
                                                >
                                                    {{ formData.share }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="币种"
                                                    prop="currencyId"
                                                >
                                                    {{formData.currency}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="截止本期末累计结算金额"
                                                    prop="cutOffAddMoney"
                                                >
                                                    {{
                                                        formData.cutOffAddMoney
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币"
                                                    prop="baseCurName"
                                                >
                                                    {{ formData.baseCurName }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="人民币汇率"
                                                >
                                                    {{ formData.rmbRate }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币汇率"
                                                >
                                                    {{formData.baseCurRate}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="状态"
                                                    prop="state"
                                                >
                                                    {{
                                                         showState(
                                                            formData.state
                                                        )
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <!-- <el-col :span="12">
                            <el-form-item label="税价合计(本位币)">
                                {{ formData.taxScSumCost }}
                            </el-form-item>
                        </el-col> -->
                                        </el-row>

                                        <el-row>
                                            <el-form-item label="备注">
                                                {{formData.remarks}}
                                            </el-form-item>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item label="作废人：">
                                                    <span>{{
                                                        formData.nullifyCreator
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废原因："
                                                >
                                                    <span>{{
                                                        formData.nullifyReason
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废说明："
                                                >
                                                    <span>{{
                                                        formData.nullifyDesciption
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废时间："
                                                >
                                                    <span>{{
                                                        formData.nullifyCreated
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- 结算明细 -->
                    <div id="billingDetailsCon" class="con">
                        <div class="tabs-title" id="billingDetails">
                            结算明细
                        </div>
                        <div class="e-table">
                            <div
                                class="errorMsg"
                                v-if="errorBillingMsg.length > 0"
                            >
                                <span>
                                    {{ errorBillingMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="settlementData"
                                ref='settlementTable'
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClassName"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': settlementData, '_this': this, 'ref': 'settlementTable' }"
                            >

                                <el-table-column
                                    prop="equipmentNo"
                                    label="设备编号"
                                    min-width="170"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    label="设备名称"
                                    min-width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="结算开始时间"
                                    min-width="150"
                                    prop='settleStartTime'
                                >

                                </el-table-column>
                                <el-table-column
                                    label="结算结束时间"
                                    min-width="150"
                                    prop='settleEndTime'
                                >

                                </el-table-column>
                                <el-table-column
                                    prop="timeUnit"
                                    label="计时单位"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="leasePrice"
                                    label="租金单价(元)"
                                    min-width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="租用时间"
                                    prop="leaseTime"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="已租时间"
                                    prop="alreadyLeaseTime"
                                >

                                </el-table-column>
                                <el-table-column
                                    label="当月租金(元)"
                                    width="100"
                                    prop='monthPrice'
                                >

                                </el-table-column>
                                <el-table-column
                                    label="操作手工资(元)"
                                    width="120"
                                    prop='operatorPrice'
                                >

                                </el-table-column>
                                <el-table-column label="进场费(元)" width="120" prop='slottingFee'>

                                </el-table-column>
                                <el-table-column label="退场费(元)" width="120" prop='exitFee'>

                                </el-table-column>
                                <el-table-column
                                    label="截止本期末累计租金(元)"
                                    min-width="180"
                                    prop="cutOffAddMoney"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="报停计费标准(元)"
                                    min-width="150"
                                    prop="stopStandard"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="billid"
                            bucketName="facilitysettle"
                            v-if="objFlag.flag5"
                            :isView='true'
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <EquipmentBillingHistory
                            :billType="3029"
                            :billId="billid"
                            @historyTableHeight='historyTableHeight'
                        ></EquipmentBillingHistory>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <exaButtons :auditState="auditState" @exas="exas" v-if='formData.state !== 5' :state='formData.state' :founderId='formData.founderId' :isPrint="formData.state === 1 || formData.state === 2"></exaButtons>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import { showLoading, hideLoading, openAppClient, formatDate, webprintReport, numToChinese } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import request from '@/api/settlementManagement/equipmentBilling/mobilize'
import publics from '@/api/settlementManagement/equipmentBilling/public'
import EquipmentBillingHistory from '@/pages/settlementManagement/equipmentBilling/EquipmentBillingHistory'
import exaButtons from '@/components/common/exaButtons'

export default {
    components: {
        AttachComp,
        EquipmentBillingHistory,
        exaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            settlementData: [], // 结算明细
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            formData: {
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                baseCurSettleMoney: 0,
                billDate: '',
                billId: '',
                billNo: '',
                currency: '',
                currencyId: '',
                cutOffAddMoney: 0,
                evaluateGrade: '',
                founderId: '',
                founderName: '',
                invoiceBill: '',
                noTaxMoney: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDesciption: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                redState: 0,
                remarks: '',
                responsiblePerson: '',
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbSumSettleMoney: 0,
                settleMoney: 0,
                settleUnit: '',
                settleUnitId: '',
                share: '',
                state: 0,
                taxMoney: 0,
                taxRate: '',
                transferMonad: '',
                transferMonadId: '',
                workId: ''
            },
            objFlag: {
                flag5: false
            },
            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转,
            formDataRules: {
                settleUnit: [
                    {
                        required: true,
                        message: '请填写结算单位',
                        trigger: 'blur'
                    }
                ],
                noTaxMoney: [
                    {
                        required: true,
                        message: '请填写结算金额(不含税)',
                        trigger: 'blur'
                    }
                ],
                settleMoney: [
                    {
                        required: true,
                        message: '请填写结算金额',
                        trigger: 'blur'
                    }
                ],

                cutOffAddMoney: [
                    {
                        required: true,
                        message: '请填写截止本期末累计结算金额',
                        trigger: 'blur'
                    }
                ],
                responsiblePerson: [
                    {
                        required: true,
                        message: '请选择经办人',
                        trigger: 'blur'
                    }
                ],

                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'blur' }
                ],

                baseCurName: [
                    {
                        required: true,
                        message: '请选择本位币',
                        trigger: 'blur'
                    }
                ]
            },
            isBatch: true,
            MouseEnterId: null,
            MouseEnterIdF: null,
            auditState: {},
            auditParams: {
                billId: '',
                billType: '3029',
                freeNextUnitIndex: null,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            },
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '3029',
                nullifyDescription: '',
                nullifyReason: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            errorList: [], //控制导航栏感叹号的显示
            errorBillingMsg: [], // 结算明细
            errorPlusDeductionMsg: [], // 加扣款
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            redFormData: null,
            isBaseCurRate: true,
            historyData: [],
            isSubmit: false,
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        //状态

        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 20 - this.lastConHeight
        }
    },
    watch: {
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' (newData, oldData) {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isBaseCurRate = true
                this.formData.baseCurRate = 1
            } else {
                this.isBaseCurRate = false
                if (oldData != '') {
                    this.formData.baseCurRate = null
                }
            }
        },
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.auditParams.billId = this.$route.query.billid
        this.getAllData()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'billingDetails', 'accessory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop + 20
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 50 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setPopConfirm', 'setAuditParams', 'setSelectedInfo']),
        //如果是新增后,直接跳转到编辑页的情况需要跳转到第二个标签
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        getAllData () {
            showLoading()
            Promise.all([
                this.getBasicInfo(), //进入页面就获取基本信息数据
                this.getAttach(), // 附件列表
                this.getUnitInfo() // 获取按钮状态
            ]).finally(() => {
                hideLoading()
            })
        },

        //获取基本信息数据
        async getBasicInfo () {
            let data = await request.getBasicInfo(this.billid)
            this.redFormData = this._.cloneDeep(data)
            this.formData = data

            // 监听结算金额(不含税)
            this.$watch('formData.noTaxMoney', () => {
                // 税额 = 结算金额(不含税) * 税率
                this.formData.taxMoney =
                    (+this.formData.noTaxMoney * (+this.formData.taxRate / 100)).toFixed(2)
                // 结算金额 = 结算金额(不含税) + 税额
                this.formData.settleMoney =
                    +this.formData.noTaxMoney + +this.formData.taxMoney
            })

            // 监听税率
            this.$watch('formData.taxRate', () => {
                this.formData.taxMoney =
                    (+this.formData.noTaxMoney * (+this.formData.taxRate / 100)).toFixed(2)
            })

            // 监听税额
            this.$watch('formData.taxMoney', () => {
                // 结算金额 = 结算金额(不含税) + 税额
                this.formData.settleMoney =
                    +this.formData.noTaxMoney + +this.formData.taxMoney
            })
            await this.getSettlement() // 结算明细
        },
        // 基本信息-调动单
        async transferMonadClick () {
            let res = await request.transferMonadClick()
            let data = res[0]
            this.formData.transferMonad = data.billNo // 调动单
            this.formData.transferMonadId = data.billId // 调动单id
            this.formData.settleUnit = data.transferOrg // 结算单位
            this.formData.settleUnitId = data.transferOrgId // 结算单位id
            this.formData.taxRate = data.tax // 税率
        },

        // 基本信息-选择经办人
        async responsiblePersonClick () {
            let res = await request.getBorrow()
            this.formData.responsiblePerson = res[0].userName
        },

        // 当币种切换时,获取人民币汇率
        async currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种名称
            let res = await publics.getRmbRate({
                //获取机构下某币种的人民币汇率
                currency: val,
                orgId: this.userInfo.orgInfo.orgId
            })
            this.formData.rmbRate = res.rate
        },
        // 本位币汇率失去焦点时
        baseCurRateBlur () {
            if (this.formData.baseCurRate == 0) {
                this.formData.baseCurRate = null
            }
        },
        // --------------------------------结算明细----------------------------

        // 结算明细
        async getSettlement () {
            let res = await request.getSettlement(this.billid)
            this.settlementData = res
        },
        async selectDevice () {
            let data = await request.selectDevice(
                this.formData.transferMonadId
            )
            let arr = []
            arr = data.map(item => {
                return {
                    alreadyLeaseTime: '', // 已租时间
                    billId: this.billid, // 设备调动结算
                    changeType: 1,
                    cutOffAddMoney: 0, //截止本期末累计租金
                    dtlId: item.transferDtlId, //弹窗明细id
                    equipmentName: item.equipmentName, // 设备名称
                    equipmentNo: item.equipmentNo, // 设备编号
                    exitFee: item.exitPrice, // 退场费
                    facilityTransferSettleDtlId: '', // 主键
                    leaseExit: '', // 租赁退场时间
                    leasePrice: item.leasePrice, // 租金单价
                    leaseTime: '', // 租赁时间
                    monthPrice: '', // 当月租金
                    operatorPrice: item.operatingSalary, // 操作手工资
                    previousAddPrice: '', // 往期累计当月租金
                    previousLeaseTime: 0, // 往期租赁时间
                    previousSettleEndDate: '', // 上期结算时间
                    settleBillNo: '', // 结算编号
                    settleEndTime: formatDate(new Date(), 'yyyy-MM-dd'), // 结算结束时间
                    settleStartTime: formatDate(new Date(), 'yyyy-MM-dd'), // 结算开始时间
                    slottingFee: item.enterPrice, // 进场费
                    specificationModel: item.specificationModel, // 规格型号
                    stopStandard: '', // 报停计费标准（元）
                    timeUnit: item.timeUnit // 计时单位
                    // oldEntranceMoney: item.enterPrice, // 记录合同带入的进场费,在修改时不能超过
                    // oldExitMoney: item.exitPrice, // 记录合同带入的退场费,在修改时不能超过
                }
            })
            // 将不同的设备添加进入表格
            arr.forEach(item => {
                const isPush = this.settlementData.every(
                    i => i.dtlId !== item.dtlId
                )
                if (isPush) {
                    this.settlementData.push(item)
                } else {
                    const newArr = this.settlementData.filter(
                        itm => itm.dtlId === item.dtlId
                    )
                    const indirectPush = newArr.some(m => m.changeType !== -1)
                    if (!indirectPush) {
                        this.settlementData.push(item)
                    }
                }
            })

            // 选择好了数据,就需要先获取一次报停费,租赁退场时间等
            await this.aloneData()

            // 结算金额(不含税) = 当月租金+操作手工资+进场费+退场费
            this.formData.noTaxMoney = this.settlementData.reduce(
                (prev, c) => prev += ((+c.monthPrice || 0) + (+c.operatorPrice || 0) + (+c.slottingFee || 0) + (+c.exitFee || 0)),
                0
            )
        },
        // 获取表格数据的报停费等
        async aloneData () {
            this.settlementData.forEach(async item => {
                let res = await request.aloneData({
                    contractId: this.formData.transferMonadId,
                    equipmentNo: item.equipmentNo,
                    startTime: item.settleStartTime,
                    endTime: item.settleEndTime,
                    type: 1
                })
                item.leaseExit = res.leaseExit // 租赁退场时间
                item.previousLeaseTime = res.previousLeaseTime // 往期租赁时间
                item.previousSettleEndDate = res.previousSettleEndDate // 上期结算时间
                item.stopStandard = res.stopStandard // 报停费用
            })
        },
        // 如果结算开始时间或者结算结束时间变化了,需要重新调接口获取报停计费标准等信息
        async settleStartTimeChange (row) {
            let res = await request.aloneData({
                contractId: this.formData.transferMonadId,
                equipmentNo: row.equipmentNo,
                startTime: row.settleStartTime,
                endTime: row.settleEndTime,
                type: 1
            })
            row.leaseExit = res.leaseExit // 租赁退场时间
            row.previousLeaseTime = res.previousLeaseTime // 往期租赁时间
            row.previousSettleEndDate = res.previousSettleEndDate // 上期结算时间
            row.stopStandard = res.stopStandard // 报停费用
        },
        // 当月租金失去焦点时
        monthPriceBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            // 租赁时间 = 当月租金/租金单价
            if (row.monthPrice && row.leasePrice) {
                row.leaseTime = (+row.monthPrice / +row.leasePrice).toFixed(2)
            }
            // 已租时间 = 租赁时间 + 往期租赁时间
            row.alreadyLeaseTime = +row.leaseTime + +row.previousLeaseTime
            // 截止本期末累计租金 = 当月租金 + 往期累计当月租金
            row.cutOffAddMoney = +row.monthPrice + +row.previousAddPrice

            // 结算金额(不含税) = 当月租金+操作手工资+进场费+退场费
            this.formData.noTaxMoney = this.settlementData.reduce(
                (prev, c) => prev += ((+c.monthPrice || 0) + (+c.operatorPrice || 0) + (+c.slottingFee || 0) + (+c.exitFee || 0)),
                0
            )
        },
        // 操作手工资(元)
        operatorPriceBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            // 结算金额(不含税) = 当月租金+操作手工资+进场费+退场费
            this.formData.noTaxMoney = this.settlementData.reduce(
                (prev, c) => prev += ((+c.monthPrice || 0) + (+c.operatorPrice || 0) + (+c.slottingFee || 0) + (+c.exitFee || 0)),
                0
            )
        },
        // 进场费(元)
        slottingFeeBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            // 进场费累计不能超合同对应的进场费,  差带入进场费的字段
            if (row.oldEntranceMoney) {
                if (!!row.slottingFee > !!row.oldEntranceMoney) {
                    row.slottingFee = ''
                    this.clientPop(
                        'err',
                        `不能超合同对应的进场费,合同进场费为${row.oldEntranceMoney}`
                    )
                }
            }

            // 结算金额(不含税) = 当月租金+操作手工资+进场费+退场费
            this.formData.noTaxMoney = this.settlementData.reduce(
                (prev, c) => prev += ((+c.monthPrice || 0) + (+c.operatorPrice || 0) + (+c.slottingFee || 0) + (+c.exitFee || 0)),
                0
            )
        },
        // 退场费(元)
        exitFeeBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            // 累计退场费不能超合同退场费, 差带入退场费的字段
            if (row.oldExitMoney) {
                if (+row.exitFee > +row.oldExitMoney) {
                    row.exitFee = ''
                    this.clientPop(
                        'err',
                        `不能超合同对应的退场费,合同退场费为${row.oldExitMoney}`
                    )
                }
            }

            // 结算金额(不含税) = 当月租金+操作手工资+进场费+退场费
            this.formData.noTaxMoney = this.settlementData.reduce(
                (prev, c) => prev += ((+c.monthPrice || 0) + (+c.operatorPrice || 0) + (+c.slottingFee || 0) + (+c.exitFee || 0)),
                0
            )
        },
        // 开始时间
        // 结算开始时间默认为上一次结算结束时间再加1天，可修改，但不能小于上一次结算结束时间
        limitTimeStart (row) {
            return {
                disabledDate (time) {
                    // 如果没有上期结算日期,说明是第一次结算,随便选日期
                    if (!row.previousSettleEndDate) {
                        if (row.settleEndTime) {
                            // 如果已经选了结束日期,那么开始日期只能选择在结束日期之前的,需要把结束日期后的所有日期都禁用掉
                            return time > new Date(row.settleEndTime)
                        }
                    } else {
                        // 如果是有上期结算日期,开始日期需在上一次结算结束日期基础上再加1天
                        // 8.64e7 就是一天的时间
                        return (
                            time < new Date(row.previousSettleEndDate) + 8.64e7
                        )
                    }
                }
            }
        },
        // 结束时间; 结算结束时间不能小于结算开始时间
        limitTimeEnd (row) {
            return {
                disabledDate (time) {
                    if (row.settleStartTime) {
                        return time < new Date(row.settleStartTime) - 8.64e7
                    } else {
                        return time
                    }
                }
            }
        },

        // 加扣款单条删除
        settlementDelete (row) {
            row.changeType = -1
            row.monthPrice = 0
            // 结算金额(不含税) = 当月租金+操作手工资+进场费+退场费
            this.formData.noTaxMoney = this.settlementData.reduce(
                (prev, c) => prev += ((+c.monthPrice || 0) + (+c.operatorPrice || 0) + (+c.slottingFee || 0) + (+c.exitFee || 0)),
                0
            )
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },

        // -------------------在点击下面几个按钮前,需要做前置判断-------------------------
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x => x === name)
            if (index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 设置结算明细有错误时在表格上面显示的错误信息
        setErrorBillingMsg (msg) {
            let index = this.errorBillingMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorBillingMsg.push(msg)
            }
        },

        // 点击左边的Tab标签
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //保存基本信息时需要检测的
        basicInfoSave () {
            return new Promise((resolve, reject) => {
                this.$refs.formDataRef.validate(valid => {
                    if (valid) {
                        request
                            .basicInfoSave(this.formData)
                            .then(() => {
                                this.clearError('baseInfo')
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                            })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },
        // 保存结算明细
        settlementSave () {
            this.errorBillingMsg = []
            return new Promise((resolve, reject) => {
                if(this.isSubmit) {
                    // 如果点击的是提交审核才需要判断结算明细是否为空,为空时不能提交审核
                    if(this.settlementData.length < 1) {
                        this.setErrorBillingMsg('请选择需结算的数据')
                        this.setError('billingDetails')
                        reject('结算明细错误')
                        return
                    }
                }
                this.settlementData.forEach(item => {
                    !item.equipmentNo
                        ? this.setErrorBillingMsg('请填写设备编号')
                        : ''
                    !item.equipmentName
                        ? this.setErrorBillingMsg('请填写设备名称')
                        : ''
                    !item.specificationModel
                        ? this.setErrorBillingMsg('请填写规格型号')
                        : ''
                    !item.settleStartTime
                        ? this.setErrorBillingMsg('请选择结算开始时间')
                        : ''
                    !item.settleEndTime
                        ? this.setErrorBillingMsg('请选择结算结束时间')
                        : ''
                    !item.timeUnit
                        ? this.setErrorBillingMsg('请填写计时单位')
                        : ''
                    !item.leasePrice
                        ? this.setErrorBillingMsg('请填写租金单价')
                        : ''
                    !item.leaseTime
                        ? this.setErrorBillingMsg('请填写租赁时间')
                        : ''
                    !item.alreadyLeaseTime
                        ? this.setErrorBillingMsg('请填写已租时间')
                        : ''
                    !item.monthPrice
                        ? this.setErrorBillingMsg('请填写当月租金')
                        : ''
                    !item.cutOffAddMoney
                        ? this.setErrorBillingMsg('请填写截止本期末累计租金')
                        : ''
                })
                if (this.errorBillingMsg.length > 0) {
                    this.setError('billingDetails')
                    reject('结算明细错误')
                    return
                } else {
                    request
                        .settlementSave(this.settlementData)
                        .then(() => {
                            this.clearError('billingDetails')
                            resolve()
                        })
                        .catch(err => {
                            this.errorBillingMsg[0] = err.message
                            this.setError('billingDetails')
                            reject(err)
                        })
                }
            })
        },

        // 保存所有数据
        saveAll () {
            showLoading()
            this.errorList = []
            Promise.all([this.basicInfoSave(), this.settlementSave()])
                .then(() => {
                    hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(() => {
                    // this.clientPop('err', '保存失败', () => {
                    this.scorllError()
                    // })
                })
                .finally(() => {
                    hideLoading()
                })
        },

        // 提交审核
        submitReview () {
            showLoading()
            this.errorList = []
            Promise.all([this.basicInfoSave(), this.settlementSave()])
                .then(() => {
                    publics
                        .commitAudit(this.auditParams)
                        .then(() => {
                            this.clientPop('suc', '提交成功', this.handleClose)
                        })
                        .catch(() => {
                            // this.clientPop('err', '提交失败', () => {
                            this.scorllError()
                            // })
                        })
                })
                .catch(() => {
                    // this.clientPop('err', '提交失败', () => {
                    this.scorllError()
                    // })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 审核
        onAudit () {
            showLoading()
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                publics
                    .audit(auditParams)
                    .then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },

        // 撤销审核
        undoAudit () {
            showLoading()
            publics
                .undoAudit(this.auditParams)
                .then(() => {
                    this.clientPop('suc', '撤回成功', this.handleClose)
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                publics
                    .nullify(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 删除
        basicInfoDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                () => {
                    showLoading()
                    request
                        .basicInfoDelete(this.billid)
                        .then(() => {
                            this.clientPop('suc', '删除成功', this.handleClose)
                        })
                        .finally(() => {
                            hideLoading()
                        })
                }
            )
        },
        // 打印
        async print () {
            const printData = async ()=>{
                showLoading()
                try{
                    const  params =  {
                        'reportTitle': '机械设备调动结算单', //报表名
                        'orgName': this.formData.orgName, //单据机构
                        'reportQRUri': '', //报表内容URI
                        'billNo': this.formData.billNo, //单据编码
                        'summaryInfoItems': [],
                        'tables': [] //表格
                    }

                    params.summaryInfoItems = this.Stmt().basicInfo
                    params.tables.push(this.Stmt().tableList)
                    params.tables.push(await this.auditHst())
                    hideLoading()
                    return params
                }catch(err) {
                    console.log(err)
                    this.clientPop('err', '打印失败')
                    hideLoading()
                }
            }
            const data = await printData()
            webprintReport(data)
        },
        // 租赁结算单
        Stmt () {
            const basicInfo = []
            const data = this.formData
            const list = [
                ['调入机构', data.settleUnit, false],
                ['附件', '    ' + '张', false],
                ['调出机构', data.orgName, false],
                ['结算依据', data.transferMonad, false],
                ['结算日期', data.billDate, false],
                ['发票编号', data.invoiceBill, false],
                ['结算金额(不含税)', data.noTaxMoney, false],
                ['税率(%)', data.taxRate + '%', false],
                ['可抵扣税额合计(元)', data.taxMoney, false],
                ['结算金额', data.settleMoney, false],
                ['结算金额大写', numToChinese(Math.abs(data.settleMoney)), true],
                ['备注信息', data.remarks, true],
            ]
            list.forEach(item => {
                const obj = {
                    label: '标题',
                    value: '内容',
                    isFullRow: false, // 是否占整行
                }
                obj.label = item[0]
                obj.value = item[1]
                obj.isFullRow = item[2]
                basicInfo.push(obj)
            })
            // 表格数据
            const tableList = {
                'tableTitle': '结算明细',
                'tableContent': {
                    '设备编号': 'equipmentNo',
                    '设备名称': 'equipmentName',
                    '规格型号': 'specificationModel',
                    '结算开始时间': 'settleStartTime',
                    '结算结束时间': 'settleEndTime',
                    '计时单位': 'timeUnit',
                    '租金单价(元)': 'leasePrice',
                    '租用时间': 'leaseTime',
                    '已租时间': 'alreadyLeaseTime',
                    '当月租金(元)': 'monthPrice',
                    '操作手工资(元)': 'operatorPrice',
                    '进场费(元)': 'oldSlottingFee',
                    '退场费(元)': 'oldExitFee',
                    '截止本期末累计租金(元)': 'cutOffAddMoney',
                    '报停费用标准(元)': 'stopStandard',
                },
                'tableData': this.settlementData, //表格数据
            }
            return { basicInfo, tableList }
        },

        // 审核历史
        async auditHst () {
            //审核历史
            const historyList = {
                'tableTitle': '审核历史',
                'tableContent': {
                    '审核级次': 'unitName',
                    '审核人': 'assignUser',
                    '审核人岗位': 'userTitle',
                    '通知时间': 'notifyTime',
                    '审核时间': 'completeTime',
                    '审核意见': 'opinion',
                },
                'tableData': this.historyData, //表格数据
            }
            return historyList
        },

        // ---------------------------下面按钮---------------------------
        // 获取按钮状态
        async getUnitInfo () {
            this.auditState = await publics.getCurrentUnitInfo(
                this.auditParams
            )
        },

        // 点击下面几个不同的按钮做不同的操作
        exas (arg) {
            if (arg === 'submit') {
                this.isSubmit = false
                this.saveAll() // 保存所有数据
            } else if (arg === 'submitCommit') {
                this.isSubmit = true
                this.submitReview() // 保存并提交
            } else if (arg === 'audit') {
                this.onAudit() // 审核
            } else if (arg === 'undoAudit') {
                this.undoAudit() // 撤销审核
            } else if (arg === 'nullify') {
                this.nullify() // 作废
            } else if (arg === 'deleteData') {
                this.basicInfoDelete() // 删除
            } else if(arg === 'print') {
                this.print() // 打印
            }
        },

        //取消按钮
        handleClose () {
            this.$router.replace('/mobilizeSetList')
        },

        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistoryCon') && this.historyData.length > 0) {
                    const lastConHeight =
                        document.getElementById('auditHistoryCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        historyTableHeight (data) {
            this.historyData = data
        },

        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        showState (state) {
            const _state = this.$store.state.equip.equipData.settleState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
::v-deep.el-table .warning-row {
    display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
::v-deep .el-table__fixed{
        height: 100% !important
}
</style>
